package cn.com.callback;

import cn.com.callback.CallBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import cn.com.kh.KHDBConfig;
import cn.com.kh.KHUtil
import net.sf.json.JSONArray
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory

/**
 * @projectName: ngsapitask-sw
 * @className: autoUnicomSMSResult
 * @author: LiJT
 * @description: 联通短信平台发送成功回调异常时通过这个自动任务再次获取发送结果
 * @date: 2022-09-27 00:12
 * @version: 1.0
 */

public class autoUnicomSMSResult implements CallBackInvoke {
    private static final Log log = LogFactory.getLog(autoUnicomSMSResult.class);
    private static int getResInterval = 30;

    public void doCallBack(EliteBean eliteBean, String callBack, Map map, String paramString) {

        log.debug("短信平台发送短信(非催缴)短信结果开始执行------------------------------");
        String isUserFlag = KHDBConfig.getParamConfig(eliteBean, "NEWSMS");
        if (KHUtil.isNull(isUserFlag) || isUserFlag != "NEW") {
            log.warn("短信平台发送短信(非催缴)-新平台未开启使用");

        } else {
            // 获取系统配置的每次获取结果报告的时间间隔
            try {
                String getResIntervalDB = KHDBConfig.getParamConfig(eliteBean, "getResInterval");
                if (!KHUtil.isNull(getResIntervalDB)) {
                    getResInterval = Integer.parseInt(getResIntervalDB);
                }
            } catch (Exception e) {
                log.error("短信平台发送短信(非催缴)-获取系统配置的每次获取结果报告的时间间隔-异常", e);
            }

            try {
                String selectDocumentoutSQL = '''Select Top 1000 Documentout_Guid, Documentto, Account_Guid, Subscriber_Guid, msgId
                                                  From Documentout With(Nolock)
                                                 Where 1 = 1
                                                   And Status = '1'
                                                   And Doctype = '3'
                                                   And Passflag = '1'
                                                   And (Result Is Null Or Result = '')
                                                   And Resultcode Is Not Null
                                                   And Lasttrydatetime <= Dateadd(Ss, -10, Getdate())
                                                   And Isnull(Resultcount, 0) < Isnull(Resultcountlimit, 3)
                                                   And (Dateadd(Ss, ''' + getResInterval + ''' * (Isnull(Resultcount, 0) + 1), Resulttrytime) < Getdate() Or Resulttrytime Is Null Or Resulttrytime = '')
                                                 Order By Case
                                                            When Stringfield1 = '人工短信' Then
                                                             1
                                                            When Stringfield1 = '工单' Then
                                                             2
                                                            When Stringfield1 = '工单催单短信' Then
                                                             2
                                                            When Stringfield1 = '通讯录短信' Then
                                                             3
                                                            When Stringfield1 = '智慧停水发送' Then
                                                             4
                                                            When Stringfield1 = '人工批次发送' Then
                                                             4
                                                          End Asc,
                                                          Lasttrydatetime''';

                List selectDocumentoutList = eliteBean.chaxun_sql(selectDocumentoutSQL, "dataSource");
                int ListNum = selectDocumentoutList.size();
                log.debug("短信平台发送短信(非催缴)-待获取短信数量ListNum:" + ListNum);

                String updateDocSQL = "";

                String Documentout_Guid = "";
                String Account_Guid = "";
                String extInfo = "";
                String msgId = "";

                for (int i = 0; i < ListNum; i++) {
                    Map selectDocumentoutSQLMap = selectDocumentoutList.get(i);

                    Documentout_Guid = selectDocumentoutSQLMap.get("Documentout_Guid");
                    Account_Guid = selectDocumentoutSQLMap.get("Account_Guid");
                    extInfo = selectDocumentoutSQLMap.get("Subscriber_Guid");
                    msgId = selectDocumentoutSQLMap.get("msgId");

                    extInfo = KHUtil.isNull(extInfo) ? KHUtil.getIntRandom(8) : extInfo;

                    // 调用发送短信
                    JSONObject sendResultJson = resultSWSms(eliteBean, Documentout_Guid, Account_Guid, extInfo);

                    // 解析返回信息LockedBy
                    String resCode = sendResultJson.has("code") ? sendResultJson.getString("code") : "-1";
                    String resDesc = sendResultJson.has("msg") ? sendResultJson.getString("msg") : "";

                    if (resCode == "0") {

                        JSONArray reportList = sendResultJson.has("data") ? sendResultJson.getJSONArray("data") : [];

                        boolean isNoGetFlag = true;
                        for (int j = 0; j < reportList.size(); j++) {

                            String r_msgId = reportList.getJSONObject(j).getString("msgId");
                            String r_status = reportList.getJSONObject(j).getString("status");
                            String r_statusDes = reportList.getJSONObject(j).getString("statusDes");
                            String r_reportTime = reportList.getJSONObject(j).getString("reportTime");

                            if (r_msgId == msgId) {
                                isNoGetFlag = false;
                                updateDocSQL = "Update Documentout Set Result = '" + r_status + "', Resultcount = Isnull(Resultcount, 0) + 1, Finishdatetime = '" + r_reportTime + "', Modifiedby = 'SELITE', Modifieddate = Getdate(), Resulttrytime = Getdate(), Comments = '" + r_statusDes + "' Where Documentout_Guid = '" + Documentout_Guid + "' And msgId = '" + r_msgId + "'";
                                log.debug("短信平台发送短信(非催缴)-短信平台发送结果回写Documentout表SQL:" + updateDocSQL);

                                int updateDocSQLRes = eliteBean.update(updateDocSQL, "dataSource");
                                log.debug("短信平台发送短信(非催缴)-短信平台发送结果回写Documentout表SQL执行结果:" + updateDocSQLRes);
                            }
                        }

                        // 经过以上处理可能结果中并没有所以如果捞取了一次没有结果也是记录捞取次数
                        if (isNoGetFlag) {

                            updateDocSQL = "Update Documentout Set Result = Case When Isnull(Resultcount, 0) + 1 >= Isnull(Resultcountlimit, 3) Then 'UNDELIV' Else Result End, Resultcount = Isnull(Resultcount, 0) + 1, Modifiedby = 'SELITE', Modifieddate = Getdate(), Resulttrytime = Getdate(), Comments = '" + resDesc + "' Where Documentout_Guid = '" + Documentout_Guid + "' And msgId = '" + msgId + "'";
                            log.debug("短信平台发送短信(非催缴)-短信平台发送结果(未获取到)回写Documentout表SQL:" + updateDocSQL);

                            int updateDocSQLRes = eliteBean.update(updateDocSQL, "dataSource");
                            log.debug("短信平台发送短信(非催缴)-短信平台发送结果(未获取到)回写Documentout表SQL执行结果:" + updateDocSQLRes);
                        }

                    } else {
                        updateDocSQL = "Update Documentout Set Result = Case When Isnull(Resultcount, 0) + 1 >= Isnull(Resultcountlimit, 3) Then 'UNDELIV' Else Result End, Resultcount = Isnull(Resultcount, 0) + 1, Modifiedby = 'SELITE', Modifieddate = Getdate(), Resulttrytime = Getdate(), Comments = '" + resDesc + "' Where Documentout_Guid = '" + Documentout_Guid + "' And msgId = '" + msgId + "'";
                        log.debug("短信平台发送短信(非催缴)-写入短信平台接口失败！短信平台回写Documentout表SQL:" + updateDocSQL);

                        int updateDocSQLRes = eliteBean.update(updateDocSQL, "dataSource");
                        log.debug("短信平台发送短信(非催缴)-写入短信平台接口失败！短信平台回写Documentout表SQL执行结果:" + updateDocSQLRes);
                    }

                }

                log.debug("短信平台发送短信(非催缴)-短信发送状态执行完成...");

            } catch (Exception e) {
                log.error("短信平台发送短信(非催缴)-短信发送状态执行异常信息", e);
            }
        }
    }

    public static JSONObject resultSWSms(EliteBean eliteBean, String Documentout_Guid, String Account_Guid, String extInfo) {
        JSONObject resultSendSms = new JSONObject();

        log.debug("sendSWSms 参数-Documentout_Guid:" + Documentout_Guid + " Account_Guid:" + Account_Guid + " extInfo:" + extInfo);

        try {
            // 获取所需要配置
            Account_Guid = KHUtil.isNull(Account_Guid) ? "SMS_JT" : Account_Guid;
            String doSendURL = KHDBConfig.getAPIURL(eliteBean, "UnSMSURL_Result_" + Account_Guid);
            String doSendID = KHDBConfig.getParamConfig(eliteBean, "UnSMS_ID_" + Account_Guid);
            String doSendPWD = KHDBConfig.getParamConfig(eliteBean, "UnSMS_PWD_" + Account_Guid);

            String timeStamp = System.currentTimeMillis().toString();
            String signInfo = doSendID + doSendPWD + timeStamp;

            // 处理头文件
            Map<String, String> headParams = new HashMap<String, String>();
            headParams.put("Content-Type", "application/json;charset=utf-8");
            headParams.put("accept", "application/json");
            headParams.put("timestamp", timeStamp);
            headParams.put("sign", Util.getSHA256Str(signInfo));

            // 发送对象
            JSONObject postJson = new JSONObject();
            postJson.put("loginName", doSendID);
            postJson.put("ext", extInfo);
            log.debug("短信平台发送短信(非催缴)-调用SW短信结果报文：" + postJson.toString());


            String resultInfo = Util.doHttpPostUseHead(doSendURL, postJson.toString(), "UTF-8", 30000, 0, headParams);
            log.debug("短信平台发送短信(非催缴)-调用SW短信结果返回：" + resultInfo);

            JSONObject resultJson = JSONObject.fromObject(resultInfo);
            String code = resultJson.getString("code");

            resultSendSms.put("code", resultJson.getString("code"));
            resultSendSms.put("msg", resultJson.getString("msg"));

            if (code == "0") {
                resultSendSms.put("data", resultJson.getJSONArray("reportList"));
            }

            log.debug("短信平台发送短信(非催缴)-调用SW短信结果返回结果：" + resultSendSms.toString());

        } catch (Exception e1) {
            log.error("短信平台发送短信(非催缴)-调用SW短信结果异常：", e1);
            resultSendSms.put("code", "-1");
            resultSendSms.put("msg", e1.getMessage());

        }

        return resultSendSms;
    }

}
